import base64
import datetime
import json
import os
import time
import uuid
import pymysql
import requests
import xlrd
from operator import itemgetter
from Batch_Call.models import Queues, Queues_Relation, Server, Task, Queues_Or_Group, Thread_Test
from Call.packaging import seats_status
from utils.connect_redis import connect_redis
from utils.page_like import pager
from utils.data_cleaning import reconsitution_data
from utils.connect_mysql import connect_outbound, connect_crm, connect_boss
from utils.cc_authentication import authentication
from  multiprocessing import Pool
from datetime import datetime



# 查询最后队列标识
def query_finally_id():
    # 连接数据库
    connect = connect_outbound()
    cursor = connect.cursor()
    try:
        sql = "select MAX(id) from zb_queues"
        cursor.execute(sql)
        max_id = cursor.fetchall()
        if not max_id:
            return 'Q2001'
        sql1 = "select queue_number from zb_queues where id=%s"%max_id[0][0]
        cursor.execute(sql1)
        queue_number = cursor.fetchall()[0][0]
        connect.close()
        cursor.close()
        return queue_number
    except Exception as e:
        print(e)
        return 500

# 查询队列下关联的所有坐席
def query_relation_seats(queue_number):
    # 连接数据库
    connect = connect_outbound()
    cursor = connect.cursor()
    try:
        sql = "select seats_number from zb_queues_relation where queue_number='%s'"%queue_number
        cursor.execute(sql)
        data = cursor.fetchall()
        data_list = []
        for i in data:
            data_list.append(i[0])
        connect.close()
        cursor.close()
        return {"code":200,"msg":"查询成功","data":{"queue_number":queue_number,"seats_number":data_list}}
    except Exception as e:
        print(e)
        return {"code":500,"msg":"系统繁忙","error":str(e)}

# print(query_relation_seats("Q2003"))

# 队列绑定/解绑
def queue_mappings(*args,**kwargs):
    # "1":绑定，"2":解绑 "3":覆盖式绑定（同时解绑座席与其他队列的关系）"4":解绑指定队列的所有坐席
    action = kwargs.get('action','')
    # 坐席工号
    agentNo = kwargs.get('agentNo','')
    # 队列id
    queueId = kwargs.get('queueId','')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/AgentQueueMappings".format(account,app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')),"utf-8")
        headers = {
            "Authorization":token,
            "Content-Type":"application/json;charset=utf-8",
            "Accept":"application/json"
        }
        data = {
            "action":action,
            "agentNo":agentNo,
            "queueId":queueId
        }
        res = requests.post(url=url,headers=headers,data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            # 解绑队列下所有坐席
            if action == '4':
                queues_relation = Queues_Relation.objects.filter(queue_number=queueId)
                if not queues_relation:
                    return {"code": 403, "msg": "关系不存在"}
                for data in queues_relation:
                    data.delete()
            # 解绑
            elif action == '2':
                queues_relation = Queues_Relation.objects.filter(queue_number=queueId,seats_number=agentNo).first()
                if not queues_relation:
                    return {"code":403,"msg":"关系不存在"}
                queues_relation.delete()
            # 存入队列关系表
            else:
                Queues_Relation(queue_number=queueId, seats_number=agentNo).save()
            return {"code":200,"msg":"成功"}
        else:
            return {"code":403, "msg":res['statusMsg']}
    except Exception as e:
        return {"code":10001,"msg":"请检查传入参数","error":str(e)}

# 查询坐席-队列绑定关系
def query_binding(*args,**kwargs):
    # 坐席工号
    agentNo = kwargs.get('agentNo', '')
    # 队列id
    queueId = kwargs.get('queueId', '')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/AgentQueueMappings/query".format(account,app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')),"utf-8")
        headers = {
            "Authorization":token,
            "Content-Type":"application/json;charset=utf-8",
            "Accept":"application/json"
        }
        data = {
            "agentNo":agentNo,
            "queueId":queueId
        }
        res = requests.post(url=url,headers=headers,data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            return {"code":200,"msg":"成功","data":res['data']}
        else:
            return {"code":403, "statusCode":res['statusCode'],"msg":res['statusMsg']}
    except Exception as e:
        return {"code":10001,"msg":"请检查传入参数","error":str(e)}

# 创建队列
def create_queues(*args,**kwargs):
    queueId = kwargs.get('queueId','') # 队列ID，应用下唯一
    description = kwargs.get('description','') # 描述
    priority = kwargs.get('priority','') # 优先级
    userCli = kwargs.get('userCli','') # 主叫线标识
    prompt = kwargs.get('prompt','') # 排队等待提示音
    timeout = kwargs.get('timeout','') # 超时时间
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/Queues/create".format(account,
                                                                                                                app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "queueId": queueId,
            "description": description,
            "priority": priority,
            "userCli": userCli,
            "prompt": prompt,
            "timeout": timeout
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            # 创建到数据库
            Queues(queue_number=queueId).save()
            return {"code": 200, "msg": "创建成功"}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 修改队列
def update_queues(*args,**kwargs):
    queueId = kwargs.get('queueId', '')  # 队列ID，应用下唯一
    description = kwargs.get('description', '')  # 描述
    priority = kwargs.get('priority', '')  # 优先级
    userCli = kwargs.get('userCli', '')  # 主叫线标识
    prompt = kwargs.get('prompt', '')  # 排队等待提示音
    timeout = kwargs.get('timeout', '')  # 超时时间
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/Queues/update".format(account,
                                                                                                            app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "queueId": queueId,
            "description": description,
            "priority": priority,
            "userCli": userCli,
            "prompt": prompt,
            "timeout": timeout
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            return {"code": 200, "msg": "修改成功"}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 删除队列
def delete_queues(*args,**kwargs):
    queueId = kwargs.get('queueId', '')  # 队列ID，应用下唯一
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/Queues/delete".format(account,
                                                                                                            app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "queueId": queueId
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            queue_number = Queues.objects.filter(queue_number=queueId).first()
            if not queue_number:
                return {"code":403,"msg":"队列ID不存在"}
            # 删除数据库中的队列ID
            queue_number.delete()
            return {"code": 200, "msg": "删除成功"}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 查询队列
def query_queues(*args,**kwargs):
    queueIds = kwargs.get('queueIds',[])
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/Queues/query".format(account,
                                                                                                                app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "queueIds": queueIds
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            return {"code": 200, "msg": "查询成功","data":res['data']}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 查询所有队列id
def query_all_queues(*args,**kwargs):
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/Queues/getall".format(account,
                                                                                                                app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            return {"code": 200, "msg": "查询成功","data":res['data']}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 创建服务
def create_server(*args,**kwargs):
    # 服务队列标识
    queueId = kwargs.get('queueId','')
    # 服务名称
    friendlyName = kwargs.get('friendlyName','')
    # 呼叫并发控制
    mode = kwargs.get('mode','')
    # 外呼用户的主叫线标识
    userCli = kwargs.get('userCli','')
    # 服务级呼叫接通率
    ccr = kwargs.get('ccr','')
    # 微调系数 默认为100，取值区间[50,200]
    tuning = kwargs.get('tuning','')
    # 工作日，1234567分别表示周一至周日，例"12345"（周一至周五
    workDay = kwargs.get('workDay','')
    # 工作时间，格式HHmm-HHmm，例"0800-2000"
    workTime = kwargs.get('workTime','')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallServices/create".format(account,app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')),"utf-8")
        headers = {
            "Authorization":token,
            "Content-Type":"application/json;charset=utf-8",
            "Accept":"application/json"
        }
        data = {
            "queueId":queueId,
            "friendlyName":friendlyName,
            "mode":mode,
            "userCli":userCli,
            "ccr":ccr,
            "tuning":tuning,
            "workDay":workDay,
            "workTime":workTime
        }
        res = requests.post(url=url,headers=headers,data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            # 存储至数据库
            Server(server_id=res['bcsId'],queue_id=queueId,server_name=friendlyName,mode=mode,usercli=userCli,ccr=ccr,tuning=tuning,workday=workDay,worktime=workTime).save()
            return {"code":200,"msg":"创建成功","bcsId":res['bcsId']}
        else:
            return {"code":403,"msg":str(res['statusMsg'])}
    except Exception as e:
        return {"code":10001,"msg":"请检查传入参数","error":str(e)}

# 启动服务
def start_server(*args,**kwargs):
    bcsId = kwargs.get('bcsId','')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallServices/start".format(account,app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')),"utf-8")
        headers = {
            "Authorization":token,
            "Content-Type":"application/json;charset=utf-8",
            "Accept":"application/json"
        }
        data = {
            "bcsId":bcsId
        }
        res = requests.post(url=url,headers=headers,data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            server = Server.objects.filter(server_id=bcsId).first()
            if not server:
                return {"code":403,"msg":"服务不存在"}
            server.status = '1'
            return {"code":200,"msg":"启动成功"}
        else:
            return {"code":403,"msg":str(res['statusMsg'])}
    except Exception as e:
        return {"code":10001,"msg":"请检查传入参数","error":str(e)}

# 停止服务
def stop_server(*args,**kwargs):
    bcsId = kwargs.get('bcsId','')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallServices/stop".format(account,app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')),"utf-8")
        headers = {
            "Authorization":token,
            "Content-Type":"application/json;charset=utf-8",
            "Accept":"application/json"
        }
        data = {
            "bcsId":bcsId
        }
        res = requests.post(url=url,headers=headers,data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            server = Server.objects.filter(server_id=bcsId).first()
            if not server:
                return {"code": 403, "msg": "服务不存在"}
            server.status = '2'
            return {"code":200,"msg":"停止成功"}
        else:
            return {"code":403,"msg":str(res['statusMsg'])}
    except Exception as e:
        return {"code":10001,"msg":"请检查传入参数","error":str(e)}

# 更新服务
def update_server(*args,**kwargs):
    bcsId = kwargs.get('bcsId', '')
    tuning = kwargs.get('tuning', '')
    userCli = kwargs.get('userCli','')
    friendlyName = kwargs.get('friendlyName','')
    queueId = kwargs.get('queueId','')
    mode = kwargs.get('mode','')
    ccr = kwargs.get('ccr','')
    workDay = kwargs.get('workDay','')
    workTime = kwargs.get('workTime','')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallServices/update".format(
            account, app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "bcsId": bcsId,
            "tuning":tuning,
            "userCli":userCli,
            "friendlyName":friendlyName,
            "queueId":queueId,
            "mode":mode,
            "ccr":ccr,
            "workDay":workDay,
            "workTime":workTime
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":

            # 修改数据库
            server = Server.objects.filter(server_id=bcsId).first()
            if not server:
                return {"code": 403, "msg": "服务不存在"}
            server.queue_id = queueId
            server.server_name = friendlyName
            server.mode = mode
            server.usercli = userCli
            server.ccr = ccr
            server.tuning = tuning
            server.workday = workDay
            server.worktime = workTime
            server.save()
            return {"code": 200, "msg": "修改成功"}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 查询服务
def retrieve_server(*args,**kwargs):
    bcsId = kwargs.get('bcsId', '')
    page = kwargs.get('page', '0')
    if page == '1':
        page = '0'
    pageSize = kwargs.get('pageSize', '10')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallServices/retrieve".format(
            account, app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "bcsId": bcsId,
            "page":page,
            "pageSize":pageSize
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            return {"code": 200, "msg": "查询成功","data":res['data']}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}


def query_group_name(queue_id):
    # 连接数据库
    connect = connect_crm()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        sql = "select group_name from zb_team_or_group where id='%s'" % queue_id
        cursor.execute(sql)
        data_list = cursor.fetchall()
        if not data_list:
            return ""
        connect.close()
        cursor.close()
        return data_list[0].get('group_name','')
    except Exception as e:
        print(e)
        return

# 创建任务
def create_task(*args,**kwargs):
    # 队列ID
    queue_id = 'Q' + str(int(query_finally_id().split('Q')[-1]) + 1)
    # 创建服务参数
    mode = kwargs.get('mode','')
    server_ccr = kwargs.get('server_ccr')
    tuning = kwargs.get('tuning','')
    # 班组ID
    group_id = kwargs.get('group_id')
    if not group_id:
        return {"code":403,"msg":"班组ID为必须参数"}
    # 创建对应的队列
    res_queue = create_queues(queueId=queue_id)
    if res_queue.get('code','') != 200:
        return {"code":403,"msg":"创建队列失败,失败原因：%s"%res_queue.get('msg','')}
    # 查询对应坐席
    try:
        # 连接crm数据库
        connect = connect_crm()
        cursor = connect.cursor()
        sql = "select seats_priority from zb_team_or_group where id=%s"%group_id
        cursor.execute(sql)
        seats_data = cursor.fetchone()
        print(seats_data[0])
        if not seats_data:
            return {"code":403,"msg":"至少分配一个坐席"}
        for k,v in eval(seats_data[0]).items():
            # 绑定坐席
            res = queue_mappings(action='3',agentNo=k,queueId=queue_id)
            if res.get('code') != 200:
                return {"code":403,"msg":"坐席为%s绑定队列失败，失败原因：%s"%(k,res.get('msg'))}
        # 储存关系
        Queues_Or_Group(queue_number=queue_id,group_id=group_id).save()
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","error":str(e)}

    # 任务及服务名称
    friendlyName = kwargs.get('friendlyName', '')
    # 创建一个对应的服务
    # 有效工作日
    work_day = kwargs.get('work_day', '')
    # 有效工作时间
    work_time = kwargs.get('work_time', '')
    if not work_day:
        work_day = "1234567"
    if not work_time:
        work_time = "0000-2359"
    else:
        work_time = ''.join(work_time.split('-')[0].split(':')[0:2]) + '-' +  ''.join(work_time.split('-')[-1].split(':')[0:2])
    res = create_server(queueId=queue_id, friendlyName=friendlyName, mode=mode, ccr=server_ccr, tuning=tuning, workDay=work_day,
                  workTime=work_time)
    if res.get('code','') != 200:
        return res
    # 服务ID
    server_id = res.get('bcsId','')
    call_way = kwargs.get('call_way', '')
    # 任务优先级
    priority = kwargs.get('priority', '')
    # 外呼线索模板批次
    batch = kwargs.get('batch', '')
    # 任务开始时间
    beginTime = kwargs.get('beginTime', '')
    endTime = kwargs.get('endTime', '')
    # 外显号码
    userCli = kwargs.get('userCli', '')
    username = kwargs.get('username', '')
    # 指定任务级呼叫接通率
    ccr = kwargs.get('ccr', '')
    account_tag = kwargs.get('account_tag','')
    template_id = kwargs.get('template_id','')
    # state
    state = kwargs.get('state', '')
    # if not kwargs.get('thread_data',''):
    #     # 查询线索数据
    #     thread_data = query_thread(batch=batch)
    #     thread_data_count = len(thread_data)
    #     if thread_data_count > 10000:
    #         page = thread_data_count // 10000
    #         surplus = thread_data_count % 10000
    #         if surplus == 0:
    #             pass
    #
    # else:
    #     thread_data = kwargs.get('thread_data','')

    try:
        thread_data = query_thread(batch=batch)
        leads = []
        for template in thread_data:
            leads.append({"tel":template.get('mobile'),"udata":"""{'account':'%s','lead_id':'%s'}"""%(qurey_account_name(template.get("enterprise_id")),str(template.get("id")))})
        account = authentication().get('account', '')
        app_sid = authentication().get('app_sid', '')
        password = authentication().get('password', '')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallTasks/create".format(
            account, app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }

        data = {
            "bcsId": server_id,
            "friendlyName": friendlyName,
            "priority": priority,
            "leads": leads,
            "beginTime": beginTime,
            "endTime": endTime,
            "userCli": userCli,
            "ccr": ccr,
            "state": "2"
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            Task(mode=mode,server_ccr=server_ccr,tuning=tuning,work_day=work_day,work_time=work_time,create_time=datetime.datetime.now(),username=username,account_tag=account_tag,task_id=res['taskId'], task_name=friendlyName, queue_id=queue_id, call_way=call_way, priority=priority,
                 begin_time=beginTime, end_time=endTime, usercli=userCli, ccr=ccr,template_id=template_id,group_id=group_id,batch=batch, status=state).save()
            return {"code": 200, "msg": "创建成功", "taskId": res['taskId']}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 500, "msg": "系统繁忙", "error": str(e)}

# 修改任务
def update_task(*args,**kwargs):
    # 任务标识
    taskId = kwargs.get('taskId','')
    # 服务标识
    bcsId = kwargs.get('bcsId', '')
    # 任务名称
    friendlyName = kwargs.get('friendlyName', '')
    call_way = kwargs.get('call_way', '')
    # 任务优先级
    priority = kwargs.get('priority', '')
    # 批次
    batch = kwargs.get('batch', '')
    # 任务开始时间
    beginTime = kwargs.get('beginTime', '')
    endTime = kwargs.get('endTime', '')
    # 外显号码
    userCli = kwargs.get('userCli', '')
    template_id = kwargs.get('template_id', '')
    # 指定任务级呼叫接通率
    ccr = kwargs.get('ccr', '')
    # state
    state = kwargs.get('state', '')
    # 服务参数
    mode = kwargs.get('mode', '')
    server_ccr = kwargs.get('server_ccr')
    tuning = kwargs.get('tuning', '')
    # 有效工作日
    work_day = kwargs.get('work_day', '')
    # 有效工作时间
    work_time = kwargs.get('work_time', '')
    if not work_day:
        work_day = "1234567"
    if not work_time:
        work_time = "0000-2359"
    else:
        work_time = ''.join(work_time.split('-')[0].split(':')[0:2]) + '-' + ''.join(
            work_time.split('-')[-1].split(':')[0:2])
    try:
        u_task = Task.objects.filter(task_id=taskId).first()
        # 修改服务参数
        update_server(bcsId=bcsId, tuning=tuning, userCli="", ccr=server_ccr, workDay=work_day, workTime=work_time,
                      queueId=u_task.queue_id, friendlyName="test_server", mode=mode)
        # 查询线索数据
        thread_data = query_thread(batch=batch)
        leads = []
        for template in thread_data:
            leads.append({"tel": template.get('mobile'), "udata": template.get('id')})
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallTasks/update".format(
            account, app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "bcsId": bcsId,
            "taskId":taskId,
            "priority":priority,
            "friendlyName":friendlyName,
            "leads":leads,
            "beginTime":beginTime,
            "endTime":endTime,
            "userCli":userCli,
            "ccr":ccr,
            "state":state
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            task = Task.objects.filter(task_id=taskId).first()
            if not task:
                return {"code": 403, "msg": "任务不存在"}
            task.task_name = friendlyName
            task.priority = priority
            task.call_way = call_way
            task.begin_time = beginTime
            task.end_time = endTime
            task.usercli = userCli
            task.ccr = ccr
            task.status = state
            task.template_id = template_id
            task.batch = batch
            task.mode = mode
            task.server_ccr = server_ccr
            task.tuning = tuning
            task.work_day = work_day
            task.work_time = work_time
            task.save()
            return {"code": 200, "msg": "修改成功"}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 启动任务
def start_task(*args,**kwargs):
    bcsId = kwargs.get('bcsId','')
    taskId = kwargs.get('taskId','')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallTasks/start".format(
            account, app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "bcsId": bcsId,
            "taskId":taskId,
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            task = Task.objects.filter(task_id=taskId).first()
            if not task:
                return {"code": 403, "msg": "任务不存在"}
            task.status = '1'
            task.save()
            return {"code": 200, "msg": "启动成功"}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 停止任务
def stop_task(*args,**kwargs):
    bcsId = kwargs.get('bcsId', '')
    taskId = kwargs.get('taskId', '')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallTasks/stop".format(
            account, app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "bcsId": bcsId,
            "taskId": taskId
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            task = Task.objects.filter(task_id=taskId).first()
            if not task:
                return {"code": 403, "msg": "任务不存在"}
            task.status = '2'
            task.save()
            return {"code": 200, "msg": "停止成功"}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 查询任务
def retrieve_task1(*args,**kwargs):
    bcsId = kwargs.get('bcsId','')
    taskId = kwargs.get('taskId','')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallTasks/retrieve".format(
            account, app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "bcsId": bcsId,
            "taskId": taskId
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            return {"code": 200, "msg": "查询成功","data":res['data']}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

def retrieve_task2(*args,**kwargs):
    account_tag = kwargs.get('account_tag', '')
    page = kwargs.get('page', 1)
    page_size = kwargs.get('page_size', 20)
    r = connect_redis(19)

    L = []
    for k in r.hkeys(account_tag):
            d = r.hget(account_tag, k)
            # print(json.loads(d))
            L.append(json.loads(d))
    if L:
        L.sort(key=itemgetter('create_time'), reverse=True)
        count = len(L)
        pager_data = pager(page=page, page_size=page_size, data=L)
        return {"code":200,"msg":"查询成功","total":count,"data":pager_data}
    else:
        return {"code": 200, "msg": "查询成功", "total": 0, "data": []}

def retrieve_task(*args,**kwargs):
    # 企业唯一标识
    account_tag = kwargs.get('account_tag','')
    page = kwargs.get('page',1)
    page_size = kwargs.get('page_size',10)
    # 连接数据库
    connect = connect_outbound()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        sql = "select * from zb_task where account_tag='%s'" % account_tag
        cursor.execute(sql)
        data_list = cursor.fetchall()
        count = len(data_list)
        if not data_list:
            return {"code":200,"msg":"查询成功","total":count,"data":[]}
        data_list.sort(key=itemgetter('create_time'), reverse=True)
        pager_data = pager(page=page, page_size=page_size, data=data_list)
        connect.close()
        cursor.close()
        L = []
        for data in pager_data:
            # 查询服务ID
            server_id = Server.objects.filter(queue_id=data.get('queue_id','')).first().server_id
            data['server_id'] = server_id
            # 查询模板名称
            data['template_name'] = query_template_name(data.get('template_id',''))
            # 查询班组名称
            group_name = query_group_name(data.get('group_id',''))
            data['group_name'] = group_name
            residue_data = retrieve_task1(bcsId=server_id,taskId=data.get('task_id'))
            # 线索总数
            data['call_count'] = residue_data.get('data',[{'totalLeads':0}])[0].get('totalLeads',0)
            # 剩余线索
            data['residue_call'] = residue_data.get('data',[{'leftLeads':0}])[0].get('leftLeads',0)
            # 已完成
            stocks = int(data['call_count']) - int(data['residue_call'])
            data['stocks'] = stocks
            # 进度
            try:
                data['schedule'] = str(round(stocks / int(residue_data.get('data',[{'totalLeads':0}])[0].get('totalLeads',0)) * 100,2)) + '%'
            except:
                data['schedule'] = '0.0%'
            # 创建时间
            data['create_time'] = str(data.get('create_time',''))
            # 当前并发
            data['ccr_now'] = 0
            seats_list = query_relation_seats(data.get('queue_id',''))
            seats_number_list = seats_list['data'].get('seats_number', [])
            # 坐席总数
            data['seats_count'] = len(seats_number_list)
            # 有效时间/小时
            work_time = data.get('work_time','')
            data['work_time'] = work_time.split('-')[0][0:2] + ':' + work_time.split('-')[0][2:4] + ':' + '00' + '-' + work_time.split('-')[-1][0:2] + ':' + work_time.split('-')[-1][2:4] + ':' + '00'
            # 空闲坐席
            idle = 0
            for seats in seats_number_list:
                S = seats_status(agentNo=seats)
                data1 = S.get('data', [])
                if data1:
                    if data1[0].get('callState', '') == 'idle' and data1[0].get('sipStatus', '') == '1' and data1[0].get('workStatus', '') == '1':
                        idle += 1
            data['leisure_seats'] = idle
            L.append(data)
        return {"code": 200, "msg": "查询成功", "total":count,"data": L}
    except Exception as e:
        print(e)
        return {"code": 500, "msg": "系统繁忙", "error": str(e)}

# 添加线索
def add_leads(*args,**kwargs):
    bcsId = kwargs.get('bcsId','')
    taskId = kwargs.get('taskId','')
    # 外呼线索列表最大10000个线索(例：{"tel":"","udata":"u1"})
    leads = kwargs.get('leads',[])
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallTasks/addLeads".format(
            account, app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "bcsId": bcsId,
            "taskId": taskId,
            "leads": leads
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            return {"code": 200, "msg": "添加成功"}
        else:
            return {"code": 403,"msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 查询线索
def query_thread(*args,**kwargs):
    batch = kwargs.get('batch', '')
    # 连接CRM数据库
    connect = connect_outbound()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        sql = "select * from zb_thread_test where batch='%s'" % batch
        cursor.execute(sql)
        data_list = cursor.fetchall()
        connect.close()
        cursor.close()
        return data_list
    except Exception as e:
        print(e)
        return 500

# 查询企业下的模板
def query_template(*args,**kwargs):
    account_id = kwargs.get('account_id','')
    # 连接CRM数据库
    connect = connect_crm()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        sql = "select * from zb_template where enterprise_id='%s' and modular_id=1"%account_id
        cursor.execute(sql)
        data_list = cursor.fetchall()
        connect.close()
        cursor.close()
        return {"code":200,"msg":"查询成功","data":data_list}
    except Exception as e:
        print(e)
        return 500

def import_data(request):
    try:
        try:
            server_id = request.data.get('server_id','')
            task_id = request.data.get('task_id','')
            my_file = request.FILES.get("myfile", None)
            repeat_type = request.data["repeat_type"]
            import_sign = request.data["import_sign"]
            batch = request.data.get("batch", None)
            user_id = request.data.get('user_id')
            e_id  =request.data.get('e_id')
            template_id  =request.data.get('template_id','')
            print(template_id)
        except Exception as e:
            return {'message': '缺少参数', 'code': 1005}
        if not my_file:
            return {'message': '文件上传失败', 'code': 501}
        conn = connect_outbound()
        if conn == 500:
            return {'code': 501, 'message': '数据库连接出错'}
        cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
        try:
            excel_name = my_file.name
            a = excel_name.split(".")[0] + datetime.datetime.now().strftime("%Y%m%d%H%M%S") + '.xlsx'
            destination = open(os.path.join("/zb_outbound/wenjian/", a), 'wb+') # zb_outbound
            for chunk in my_file.chunks():
                destination.write(chunk)
            destination.close()
            wb = xlrd.open_workbook('/zb_outbound/wenjian/{}'.format(a))
            sheet1 = wb.sheets()[0]
            nrows = sheet1.nrows
        except Exception as e:
            return {'message': '文件格式有误', 'code': 501,'error':str(e)}
        try:
            date = {"code": 200, "message": "ok", "data": {}}
            create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            if not batch:
                batch = str(time.time()).split(".")[0]
            r = connect_redis(16)
            if r == 500:
                return {'code': 501, 'message': '数据库连接出错'}
            r.hset(import_sign, "total", nrows - 1)
            r.hset(import_sign, "done", 0)
            add_to = request.data.get('add_to', '')
            if add_to:
                tag = uuid.uuid1()
            else:
                tag = ''
            for i in range(1, nrows):
                rows = sheet1.row_values(i)
                if rows:
                    mobile = int(rows[2])
                    thread_name = rows[0]
                    thread_source = rows[1]
                    telephone = rows[3]
                    email = rows[5]
                    level = rows[6]
                    industry = rows[7]
                    address = rows[4]
                    des = rows[8]
                    if task_id:
                        check_sql = "select id from zb_thread_test where mobile='{}' and batch='{}' and enterprise_id='{}'".format(mobile,batch,e_id)
                    else:
                        check_sql = "select id from zb_thread_test where mobile='{}' and enterprise_id='{}'".format(mobile,e_id)
                    cur.execute(check_sql)
                    check_res = cur.fetchone()
                    if check_res:
                        if int(repeat_type) == 0:
                            try:
                                update_sql = "update zb_thread_test set template_id='{}',tag='{}',u_id='{}',thread_name='{}', thread_source='{}', " \
                                             "mobile='{}', telephone='{}', email='{}',level='{}',industry='{}', " \
                                             "address='{}',des='{}', batch='{}' where id={}" \
                                    .format(template_id,tag,user_id, thread_name, thread_source, mobile, telephone, email,
                                            level, industry,
                                            address, des, batch, check_res['id'])
                                cur.execute(update_sql)
                                conn.commit()

                            except Exception as e:
                                date['data']['{}'.format(i + 1)] = '第{}行,{},覆盖错误{}'.format((i + 1), rows[0],
                                                                                           str(e))
                        else:
                            date['data']['{}'.format(i + 1)] = '第{}行,{},数据已存在'.format((i + 1), rows[0])
                    else:
                        try:
                            ins_sql = "insert into zb_thread_test (template_id,task_id,tag,u_id, enterprise_id,thread_name, thread_source, mobile, telephone, email," \
                                      " level, industry, address, des, batch, update_time, create_time) values ('{}','{}','{}','{}','{}', '{}'," \
                                      "  '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')" \
                                .format(template_id,task_id,tag,user_id,e_id, thread_name, thread_source, mobile, telephone, email,
                                        level, industry,
                                        address,
                                        des, batch, create_time, create_time)
                            cur.execute(ins_sql)
                            conn.commit()
                        except Exception as e:
                            date['data']['{}'.format(i + 1)] = '第{}行,{},插入错误{}'.format((i + 1), rows[0], str(e))
                else:
                    date['data']['{}'.format(i + 1)] = '此行没有数据'
                cur_done = r.hget(import_sign, "done")
                r.hset(import_sign, "done", int(cur_done) + 1)
            if tag and server_id and task_id:
                thread_test = Thread_Test.objects.filter(tag=tag)
                leads = []
                for thread in thread_test:
                    leads.append({"tel":thread.mobile,"udata":"""{'account':'%s','lead_id':'%s'}"""%(qurey_account_name(thread.enterprise_id),str(thread.id))})
                add_leads(bcsId=server_id, taskId=task_id, leads=leads)
        except Exception as e:
            print("批量上传失败,error:{}".format(str(e)))
            return {'message': '数据存入出错,error:{}'.format(str(e)), 'code': 501}
        return date
    except Exception as e:
        print("批量上传失败,error:{}".format(str(e)))
        return {"code": 1000, "message": "批量上传失败,error:{}".format(str(e))}

# ID查询线索数据
def get_thread_first(id):
    connect = connect_outbound()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        sql = "select * from zb_thread_test where id=%s" % id
        cursor.execute(sql)
        data_list = cursor.fetchall()
        connect.close()
        cursor.close()
        return {"messageType":"threadEvent","data_list":data_list}
    except Exception as e:
        print(e)
        return 500

# 查询企业名称
def qurey_account_name(a_id):
    # 连接CRM数据库
    connect = connect_boss()
    cursor = connect.cursor()
    try:
        sql = "select account from zb_account where id=%s" % a_id
        cursor.execute(sql)
        data = cursor.fetchone()
        connect.close()
        cursor.close()
        if not data:
            return ""
        return data[0]
    except Exception as e:
        print(e)
        return 500

# 查询模板名称
def query_template_name(template_id):
    # 连接CRM数据库
    connect = connect_crm()
    cursor = connect.cursor()
    try:
        sql = "select template_name from zb_template where id=%s" % template_id
        cursor.execute(sql)
        data = cursor.fetchone()
        connect.close()
        cursor.close()
        if not data:
            return ""
        return data[0]
    except Exception as e:
        print(e)
        return 500

def func(batch):
    # 查询线索数据
    thread_data = query_thread(batch=batch)
    thread_data_count = len(thread_data)
    if thread_data_count > 6:
        page = thread_data_count // 3
        a = thread_data_count % 3
        if a == 0:
            for i in range(page):
                pager_data = pager(page=i+1,page_size=3,data=thread_data)
                print(len(pager_data))
                print(pager_data)
        else:
            for i in range(page + 1):
                pager_data = pager(page=i+1,page_size=3,data=thread_data)
                print(len(pager_data))
                print(pager_data)

def query_account_data(*args,**kwargs):
    account_id = kwargs.get('account_tag','')
    page = kwargs.get('page', 1)
    page_size = kwargs.get('page_size', 10)
    # 连接数据库
    connect = connect_outbound()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        sql = "select * from zb_task where account_tag='%s'" % account_id
        cursor.execute(sql)
        data_list = cursor.fetchall()
        count = len(data_list)
        if not data_list:
            return [],count
        data_list.sort(key=itemgetter('create_time'), reverse=True)
        pager_data = pager(page=page, page_size=page_size, data=data_list)
        connect.close()
        cursor.close()
        return pager_data,count
    except:
        return []

def query_task(data):
    # 连接外呼数据库
    connect = connect_outbound()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    # data_list = kwargs.get('data_list',[])
    # count = kwargs.get('count',0)
    # L = []
    # 查询服务ID
    sql3 = "select server_id from zb_server where queue_id='%s'" % data.get('queue_id', '')
    cursor.execute(sql3)
    server_id = cursor.fetchall()
    if not server_id:
        server_id = ''
    else:
        server_id = server_id[0].get('server_id', '')
    data['server_id'] = server_id
    # 查询模板名称
    data['template_name'] = query_template_name(data.get('template_id', ''))
    # 查询班组名称
    group_name = query_group_name(data.get('group_id', ''))
    data['group_name'] = group_name
    residue_data = retrieve_task1(bcsId=server_id, taskId=data.get('task_id'))
    # 线索总数
    data['call_count'] = residue_data.get('data', [{'totalLeads': 0}])[0].get('totalLeads', 0)
    # 剩余线索
    data['residue_call'] = residue_data.get('data', [{'leftLeads': 0}])[0].get('leftLeads', 0)
    # 已完成
    stocks = int(data['call_count']) - int(data['residue_call'])
    data['stocks'] = stocks
    # 进度
    try:
        data['schedule'] = str(
            round(stocks / int(residue_data.get('data', [{'totalLeads': 0}])[0].get('totalLeads', 0)) * 100,
                  2)) + '%'
    except:
        data['schedule'] = '0.0%'
    # 创建时间
    data['create_time'] = str(data.get('create_time', ''))
    # 当前并发
    data['ccr_now'] = 0
    seats_list = query_relation_seats(data.get('queue_id', ''))
    seats_number_list = seats_list['data'].get('seats_number', [])
    # 坐席总数
    data['seats_count'] = len(seats_number_list)
    # 有效时间/小时
    work_time = data.get('work_time', '')
    data['work_time'] = work_time.split('-')[0][0:2] + ':' + work_time.split('-')[0][2:4] + ':' + '00' + '-' + \
                        work_time.split('-')[-1][0:2] + ':' + work_time.split('-')[-1][2:4] + ':' + '00'
    # 空闲坐席
    idle = 0
    for seats in seats_number_list:
        S = seats_status(agentNo=seats)
        data1 = S.get('data', [])
        if data1:
            if data1[0].get('callState', '') == 'idle' and data1[0].get('sipStatus', '') == '1' and data1[0].get(
                    'workStatus', '') == '1':
                idle += 1
    data['leisure_seats'] = idle
    return data

def run(*args,**kwargs):
    try:
        account_tag = kwargs.get('account_tag','')
        if not account_tag:
            return {"code":403,"msg":"企业标识为必须参数"}
        page = kwargs.get('page',1)
        page_size = kwargs.get('page_size',10)
        start_time = datetime.now()
        pool = Pool(5)  # 创建一个5个进程的进程池
        # seats_list = ["3001", "3002", "3003", "3004", "3005"] * 100
        data_list = query_account_data(account_tag=account_tag,page=page,page_size=page_size)
        count = data_list[-1]
        pool_list = []
        for i in data_list[0]:
            pool_list.append(pool.apply_async(func=query_task, args=(i,)))
        pool.close()
        pool.join()
        L = []
        for data in pool_list:
            if data.get():
                L.append(data.get())
        print('结束', datetime.now() - start_time)
        return {"code":200,"msg":"查询成功","total":count,"data":L}
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","error":str(e)}

# func('20210506105732162')

# print(queue_mappings(action="1",agentNo="3004",queueId="Q2009"))
# print(query_relation_seats(queue_number='Q2009'))
# print(query_binding(queueId='Q2012',agentNo='3002'))
# print(create_queues(queueId='Q' + str(int(query_finally_id().split('Q')[-1]) + 1)))
# print(query_queues(queueIds=["Q2001","Q2002"]))
# print(delete_queues(queueId="Q2009"))
# print(query_all_queues())
# print(update_queues(queueId="Q2002",description="修改测试队列",priority="10",timeout="20"))
# print(create_server(queueId="Q2007",mode="1",friendlyName="testService",userCli="02860695190",ccr="50",tuning="80",workDay="1234567",workTime="0000-2359"))
# print(start_server(bcsId="10000"))
# print(stop_server(bcsId="10000"))
# print(update_server(bcsId="8",tuning="50",userCli="",ccr="50",workDay="1234567",workTime="0000-2359",queueId="Q2007",friendlyName='testserver',mode='1'))
# print(retrieve_server(bcsId="9",page="0",pageSize="10"))
# print(retrieve_task1(bcsId="73",taskId="125"))
# print(update_task(taskId="2",bcsId="3",friendlyName="testTask",leads=[{"tel":"13389545453","udata":"马菲菲电话测试"}],priority="10",userCli="02860695190",state="1",ccr="100",beginTime="2021-03-29 13:47:00"))
# print(create_task(bcsId="2",friendlyName="testTask",leads=[{"tel":"13389545453","udata":"马菲菲电话测试"},{"tel":"16619980636","udata":"电话测试"}],priority="10",userCli="02860695190",state="2",ccr="100",beginTime="11"))
# print(start_task(bcsId="20",taskId="63"))
# print(add_leads(bcsId="17",taskId="21",leads=[{"tel":"17610572690","udata":"于全胜"},{"tel":"13389545453","udata":"马菲菲测试电话"}]))